//
//  TimeSettingDetailView.m
//  TaiHao
//
//  Created by rzm on 16/6/3.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxInstallTimeDetailView.h"
//#import "SmapuxTimeChooseCellSub.h"
//#import "InstallTimeView.h"
#import "SampuxInstallDetailTimeModel.h"
#import "SmpuxTimePickerView.h"
#import "SPTimeValue.h"
#import "SPSetProgramInfo.h"
#import "SampuxGlobalTool.h"
@interface SampuxInstallTimeDetailView ()<DateInstallViewChangeDateDelegate,DateChangeHourDelegate>
{
    NSMutableArray *timeArr;
    NSArray *temArr;
}

@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIView *installView ;
@property (nonatomic, strong) NSMutableArray *btnArr;
//@property (nonatomic, strong) InstallTimeView *timeViewHour;
//@property (nonatomic, strong) InstallTimeView *timeViewMin;
//@property (nonatomic, strong) InstallTimeView *speedView;
@property (nonatomic, strong) SmpuxTimePickerView *dateInstallView;
@property (nonatomic, strong) SampuxTimeChooseView *chooseTimeView;
@property (nonatomic, strong) NSMutableArray *chooseTimeCellArr;

@end

@implementation SampuxInstallTimeDetailView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setTime:) name:NOTIFICATION_RESPONSE_SET_PROGRAM object:nil];
        _chooseTimeCellArr = [NSMutableArray array];
        _btnArr = [NSMutableArray array];
        [self loadUI];
    }
    return self;
}

- (void)loadUI
{
    CGFloat font;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }
    UIView *weekView = [[UIView alloc]initWithFrame:CGRectMake(-1, 64, self.width+2, Sampux6HScale(88))];
    weekView.layer.borderWidth = 1;
    [self addSubview:weekView];
    weekView.layer.borderColor = THWhiteAlplaColor(0.3).CGColor;
    
    NSArray *titleArr = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"全选"];
    for (int i = 0 ; i < 8; i ++) {
        
        CGFloat W = weekView.width/4;//设置按钮坐标及大小
        CGFloat H = weekView.height/2;
        CGFloat X = (i%4)*W;
        CGFloat Y = floor(i/4)*H;
        UIButton *dateBtn = [UIButton createButtonWithTitle:titleArr[i] titleFont:THFont(14) titleColor:THWhiteAlplaColor(0.8)];
        dateBtn.frame = CGRectMake(X, Y, W, H);
        dateBtn.layer.borderColor = THWhiteAlplaColor(0.3).CGColor;
        dateBtn.layer.borderWidth = 0.5;
        [weekView addSubview:dateBtn];
        dateBtn.tag = i + 10000;
        if (i == 7) {
            self.dateBtn = dateBtn;
        }else
        {
            [_btnArr addObject:dateBtn];
        }
        dateBtn.selected = NO;
        [dateBtn setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
        [dateBtn addTarget:self action:@selector(dateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, weekView.bottom, self.width, (self.height) * 0.3)];
    [self addSubview:backView];
    backView.contentMode = UIViewContentModeScaleAspectFit;
    backView.layer.masksToBounds = YES;

    UIView *installView = [[UIView alloc] initWithFrame:CGRectMake(0, backView.height/2 - Sampux6HScale(160)/2, backView.width, Sampux6HScale(160))];
    [backView addSubview:installView];
    installView.contentMode = UIViewContentModeScaleAspectFit;
    installView.layer.masksToBounds = YES;
//    UIView *installView = [[UIView alloc]initWithFrame:CGRectMake(0, weekView.bottom, self.width, Sampux6HScale(216))];
//    installView.contentMode = UIViewContentModeScaleAspectFit;
//    installView.layer.masksToBounds = YES;
//    [self addSubview:installView];
    self.installView = installView;
    [self createDateInstallView];
    
    SampuxTimeChooseView *chooseTimeView = [[SampuxTimeChooseView alloc]initWithFrame:CGRectMake(0,backView.bottom, self.width, (self.height) * 0.3)];
    [self addSubview:chooseTimeView];
    self.chooseTimeView = chooseTimeView;
    __weak typeof(SampuxInstallTimeDetailView *) wSelf = self;
    chooseTimeView.cellSelectedBlock = ^{
        NSDateFormatter* formater = [[NSDateFormatter alloc] init];
        [formater setDateFormat:@"HH:mm"];

        NSString *sepTime = [SPTimeValue separatedTimeValueWithString:wSelf.chooseTimeView.selectedCell.timeLabel.text];
        NSString *timStr = [SPTimeValue setTimeValue:sepTime];
//        NSDate* date = [formater dateFromString:timStr];
//        _dateInstallView.datePicker.date = date;
        NSString *hourStr = [[timStr componentsSeparatedByString:@":"] firstObject];
        NSString *minStr = [[timStr componentsSeparatedByString:@":"] lastObject];

        _dateInstallView.hourPicker.hourStr = hourStr;
        _dateInstallView.hourPicker.minStr = minStr;
        _dateInstallView.hourPicker.pickerInitialRow = [self handleHourValue:hourStr];
        _dateInstallView.hourPicker.pickerMinInitialRow = [self handleMinValue:minStr];
        NSArray *speedTextArr = [wSelf.chooseTimeView.selectedCell.speedLabel.text componentsSeparatedByString:@"℃"];
        _dateInstallView.pickerInitialRow = [self handleValue:speedTextArr[0]];
    };
    UIView *btnBackView = [[UIView alloc]initWithFrame:CGRectMake(0, chooseTimeView.bottom, self.width, self.height - chooseTimeView.bottom)];
    [self addSubview:btnBackView];
    
    [UIView createLineViewInTop:btnBackView];
    UIButton *yesBtn = [UIButton createButtonWithTitle:@"保存" frame:CGRectMake(btnBackView.width *0.2, btnBackView.height/2 -  Sampux6HScale(40)/2 , btnBackView.width* 0.6, Sampux6HScale(40)) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [btnBackView addSubview:yesBtn];
    yesBtn.layer.borderWidth = 1;
    yesBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    [yesBtn addTarget:self action:@selector(yesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [yesBtn setCorner: yesBtn.height/2];
    timeArr = [NSMutableArray array];
    [self.chooseTimeView setSelectedCellType:THChooseTimeCellType_Morning];
}

- (void)createDateInstallView
{
    CGFloat Y = self.installView.height * 0.1;
    CGFloat H = self.installView.height * 0.8;
    CGFloat W = self.installView.width*0.84;
    _dateInstallView = [[SmpuxTimePickerView alloc]initWithFrame:CGRectMake(self.installView.width * 0.08, Y, W, H)];
//    _dateInstallView.TempArr = self.tempArr;
    _dateInstallView.layer.masksToBounds = YES;
    _dateInstallView.hourPicker.installDelegate = self;
    _dateInstallView.installDelegate = self;
//    _dateInstallView.contentMode = UIViewContentModeScaleAspectFit;
    [self.installView addSubview:_dateInstallView];
}

- (void)setTempArr:(NSArray *)tempArr
{
    _tempArr = tempArr;
    _dateInstallView.TempArr = self.tempArr;

}

#pragma mark DateInstallViewChangeDateDelegate
- (void)changeDate:(NSString *)dateStr
{
    NSLog(@"%@",dateStr);
    self.chooseTimeView.selectedCell.timeLabel.text = dateStr;
}

- (void)changeSpeed:(NSString *)speedStr
{
    self.chooseTimeView.selectedCell.speedLabel.text = [NSString stringWithFormat:@"%@℃",speedStr];
}
#pragma mark DateChangeHourDelegate
- (void)changeHourAndMin:(NSString *)hourStr andminStr:(NSString *)minStr
{
    self.chooseTimeView.selectedCell.timeLabel.text = [NSString stringWithFormat:@"%@:%@",hourStr,minStr];
}

- (void)setSelectedBtnIndex:(NSInteger)selectedBtnIndex
{
    _selectedBtnIndex = selectedBtnIndex;
    for (int i = 0; i < _btnArr.count; i ++) {
        if ( _selectedBtnIndex ==  6) {
            UIButton *btn = _btnArr[0];
            btn.selected = YES;
            [_btnArr[0] setTitleColor:THSystemRedColor forState:UIControlStateNormal];
        }else if (_selectedBtnIndex >= 0 &&_selectedBtnIndex <6)
        {
            UIButton *btn = _btnArr[_selectedBtnIndex+1];
            btn.selected = YES;
            [_btnArr[_selectedBtnIndex+1] setTitleColor:THSystemRedColor forState:UIControlStateNormal];
        }
    }
}

//- (void)getTimeString
//{
//    NSString *timeString = [NSString stringWithFormat:@"%@",self.dateInstallView.dateStr];
//    self.chooseTimeView.selectedCell.timeLabel.text = timeString;
//}
//
//- (void)getSpeedString
//{
//    NSString *speedString = [NSString stringWithFormat:@"%@ X",self.dateInstallView.speedStr];
//    self.chooseTimeView.selectedCell.speedLabel.text = speedString;
//}

- (void)dateBtnClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.tag == 10007&&btn.selected == YES) {
        for (UIButton *btn in _btnArr) {
            btn.selected = YES;
            [btn setTitleColor:THSystemRedColor forState:UIControlStateNormal];
        }
    }else if (btn.tag == 10007&&btn.selected == NO)
    {
        for (UIButton *btn in _btnArr) {
            btn.selected = NO;
            [btn setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
        }
    }

    if (btn.selected == NO) {
        [btn setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
    }else
    {
        [btn setTitleColor:THSystemRedColor forState:UIControlStateNormal];
    }
}

- (void)yesBtnClick
{
    SampuxInstallDetailTimeModel *model = [[SampuxInstallDetailTimeModel alloc]init];
    NSMutableArray *selectedBtnArr = [NSMutableArray array];

    [_btnArr enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.selected) {
            [selectedBtnArr addObject:obj];
        }
    }];
    model.selectedBtnArr = selectedBtnArr;
    model.selectedCellType = self.chooseTimeView.selectedCell.cellType;
    
    NSArray *setTimeArr = [self createProgramInfoArray];
    [setTimeArr enumerateObjectsUsingBlock:^(GBInterMaster_Bean_ProgramInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [GBInterMaster_CommForDeivce requestSetProgram:0 withDeviceAccount:self.reciveModel.deviceAccount withProgram:obj];
    }];
    
    NSArray *timeArr = [self.chooseTimeView.selectedCell.timeLabel.text componentsSeparatedByString:@":"];
    NSString *timeStr = STRING_INT([timeArr.firstObject integerValue] *60 + [timeArr.lastObject integerValue]);
    model.timeStr = timeStr;
    NSArray *speedArr = [self.chooseTimeView.selectedCell.speedLabel.text componentsSeparatedByString:@"℃"];
    model.speedStr = speedArr[0] ;
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"THNotificationCenter_settingTime" object:model];
}

- (NSInteger)getBackBtnArrWhenSelected
{
    __block NSMutableArray *binaryArr = [NSMutableArray array];
    [self.btnArr enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.selected) {
            int value = 0;
            if (idx == 0) {
                value = (int)pow(10, 6);
            }else
            {
                value = (int)pow(10, idx - 1);
            }
            [binaryArr addObject:STRING_INT(value)];
        }
    }];
     int sum = 0;
    __block NSString *weekStr = [NSString string];
    
    for (int i = 0; i <binaryArr.count; i ++) {
        int binary = [binaryArr[i] intValue];
        sum = sum + binary;
        weekStr = STRING_INT(sum);
    }
    NSInteger system = [SPSetProgramInfo setWeekDayWithBinaryToDecimalSystem:weekStr];
    return system;
}

- (NSArray *)createProgramInfoArray
{
    __block NSMutableArray *array = [NSMutableArray array];
//    [weekArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GBInterMaster_Bean_ProgramInfo *programInfo = [[GBInterMaster_Bean_ProgramInfo alloc]init];
        programInfo.deviceAccount = self.reciveModel.deviceAccount;
        programInfo.deviceType = [self.reciveModel.deviceType intValue];
        programInfo.weekDay = (int)[self getBackBtnArrWhenSelected];
//        programInfo.weekDay = [obj intValue];
        programInfo.topValue = [self.reciveModel.topValue intValue];
        programInfo.lowValue = [self.reciveModel.lowValue intValue];
        NSArray *timeArr = [self.chooseTimeView.selectedCell.timeLabel.text componentsSeparatedByString:@":"];
        NSString *minute = STRING_FORMAT(timeArr.lastObject);
        NSString *timeStr = STRING_INT([timeArr.firstObject integerValue] * 60 + [minute integerValue]);
        NSArray *speedArr = [self.chooseTimeView.selectedCell.speedLabel.text componentsSeparatedByString:@"℃"];
        programInfo.onePoint = [self.reciveModel.onePoint intValue];
        programInfo.oneValue = [self.reciveModel.oneValue intValue];
        programInfo.twoPoint = [self.reciveModel.twoPoint intValue];
        programInfo.twoValue = [self.reciveModel.twoValue intValue];
        programInfo.threePoint = [self.reciveModel.threePoint intValue];
        programInfo.threeValue = [self.reciveModel.threeValue intValue];
        programInfo.fourPoint = [self.reciveModel.fourPoint intValue];
        programInfo.fourValue = [self.reciveModel.fourValue intValue];
        if (self.chooseTimeView.selectedCellType == THChooseTimeCellType_Morning) {
            programInfo.onePoint = [timeStr intValue];
            programInfo.oneValue = [speedArr.firstObject intValue];
            
        }else if (self.chooseTimeView.selectedCellType == THChooseTimeCellType_Noon)
        {
            programInfo.twoPoint = [timeStr intValue];
            programInfo.twoValue = [speedArr.firstObject intValue];
            
        }else if (self.chooseTimeView.selectedCellType == THChooseTimeCellType_After)
        {
            programInfo.threePoint = [timeStr intValue];
            programInfo.threeValue = [speedArr.firstObject intValue];
        }else
        {
            programInfo.fourPoint = [timeStr intValue];
            programInfo.fourValue = [speedArr.firstObject intValue];
        }
        [array addObject:programInfo];
//    }];
    return array;
}

- (void)backBtnClick
{
    if (self.backBlock) {
        self.backBlock();
    }
}

- (void)setReciveModel:(SampuxInstallTimeModel *)reciveModel
{
    _reciveModel = reciveModel;
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"HH:mm"];
    NSString *timStr = [SPTimeValue setTimeValue:_reciveModel.onePoint];

    NSDate *date = [formater dateFromString:timStr];
//    _dateInstallView.datePicker.date = date;
    _dateInstallView.hourPicker.hourStr = [[timStr componentsSeparatedByString:@":"] firstObject];
    _dateInstallView.hourPicker.minStr = [[timStr componentsSeparatedByString:@":"] lastObject];

    _dateInstallView.hourPicker.pickerInitialRow = [self handleHourValue:[[timStr componentsSeparatedByString:@":"] firstObject]];

    _dateInstallView.hourPicker.pickerMinInitialRow = [self handleMinValue:[[timStr componentsSeparatedByString:@":"] lastObject]];

    _dateInstallView.pickerInitialRow = [self handleValue:_reciveModel.oneValue];
    self.dateInstallView.speedStr = _reciveModel.oneValue;
    self.chooseTimeView.initialModel = _reciveModel;
    
}

- (void)setListModel:(SampuxListModel *)listModel
{
    _listModel = listModel;
//    self.dateInstallView.TempArr = listModel.limitArr;
}


//- (void)setConfigModel:(SPDeviceConfigModel *)configModel
//{
//    _configModel = configModel;
//    self.dateInstallView.TempArr = _configModel.limitedArr;
//}


- (NSInteger)handleHourValue:(NSString *)value
{
    __block NSInteger selectIndex = 0;
    [HourArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([value isEqualToString: obj]) {
            selectIndex = idx;
            *stop = YES;
        }
    }];
    return selectIndex;
}

- (NSInteger)handleMinValue:(NSString *)value
{
    __block NSInteger selectIndex = 0;
    [MinArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([value isEqualToString: obj]) {
            selectIndex = idx;
            *stop = YES;
        }
    }];
    return selectIndex;
}

- (NSInteger)handleValue:(NSString *)value
{
    __block NSInteger selectIndex = 0;
//    [self.configModel.limitedArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if ([value isEqualToString: obj]) {
//            selectIndex = idx;
//            *stop = YES;
//        }
//    }];
    [self.tempArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([value isEqualToString: obj]) {
            selectIndex = idx;
            *stop = YES;
        }
    }];
    return selectIndex;
}

- (void)setTime:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"setTime == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        
        [SVProgressHUD showSuccessWithStatus:@"设置时段成功"];
//        [MBProgressHUD showError:@"设置时段成功"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setTimeSuccess" object:nil];
//        if (self.makeSureBlock) {
//            self.makeSureBlock();
//        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dateBtn.selected = NO;
            [self.dateBtn setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
            
            [self.btnArr enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.selected = NO;
                [obj setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
                
            }];
        });
    }else if (responseCode == 0x08)
    {
        [SVProgressHUD showErrorWithStatus:@"设备未在线"];
//        [MBProgressHUD showError:@"设备未在线"];
    }else
    {
//        [MBProgressHUD showError:@"设置时段失败"];
        [SVProgressHUD showErrorWithStatus:@"设置时段失败"];

    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
